import {message} from 'antd'
import { Effect, ImmerReducer, history } from 'umi';
// 数据请求的方法
import { loginFn } from '@/api/user';

// 定义全局状态管理中数据的类型
export interface AdminModelState {
  adminname: string;
  role: number;
  checkedkeys: string[],
  loginState: boolean,
  token: string
}

// 用来给 AdminModel 添加类型用的
export interface AdminModelType {
  namespace: 'admin';
  state: AdminModelState;
  effects: {
    loginAction: Effect;
  };
  reducers: {
    // change_info: Reducer<AdminModelState>;
    // 启用 immer 之后
    change_info: ImmerReducer<AdminModelState>;
  };
}

// 创建全局状态管理模块
const AdminModel: AdminModelType = {
  namespace: 'admin',
  state: {
    adminname: localStorage.getItem('adminname') || '',
    role: Number(localStorage.getItem('role')) || 1,
    checkedkeys: JSON.parse(localStorage.getItem('checkedkeys') as string) || [],
    loginState: localStorage.getItem('loginState') === 'true',
    token: localStorage.getItem('token') || ''
  },
  // 用来放异步的地方
  effects: {
    *loginAction({ payload }, { call, put }): any{
      // 异步函数
      const res = yield call(loginFn,payload)
      // console.log('11111111111111111111',res);
      if(res.data.code != '200'){
        // 密码错误
        message.error(res.data.message)
      }else {
        // 登录成功
        message.success('恭喜你登录成功')
        // 触发 reducers 中的函数用的
        yield put({
          type: 'change_info',
          payload: res.data.data
        })
      }

    }
  },
  // 修改全局状态的地方
  reducers: {
    change_info(state: AdminModelState, action: any){
      // console.log(state, action.payload);
      // 保存到本地
      localStorage.setItem('adminname', action.payload.adminname)
      localStorage.setItem('role', action.payload.role)
      localStorage.setItem('checkedkeys', JSON.stringify(action.payload.checkedkeys))
      localStorage.setItem('loginState', action.payload.loginState)
      localStorage.setItem('token', action.payload.token)

      // 保存在全局状态管理
      state.adminname = action.payload.adminname
      state.role = action.payload.role
      state.checkedkeys = action.payload.checkedkeys
      state.loginState = action.payload.loginState
      state.token = action.payload.token

      // 跳转到首页
      history.push('/');
    }
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  }
};

export default AdminModel;
